import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles } from 'src/decorator/roles.decorator';
import { TokenService } from 'src/service/token.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly tokenService: TokenService,
  ) {}
  hasIntersection(arr1: string[], arr2: string[]) {
    return arr1.some((item) => arr2.includes(item));
  }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const roles = this.reflector.get(Roles, context.getHandler());
    if (!roles || !roles.length) {
      return true;
    }
    const token = request.headers['authorization'];

    const res = await this.tokenService.decoded(token);
    const userRoles = res.role.map((el) => el.key);
    if (this.hasIntersection(userRoles, roles)) {
      return true;
    }
    throw new HttpException('无权限', HttpStatus.FORBIDDEN);
  }
}
